-- https://www.cnblogs.com/xiii/p/12433798.html
app = LibStub("AceAddon-3.0"):NewAddon("oUF", "AceConsole-3.0", "AceEvent-3.0")


-- 首次加载插件时
function app:OnInitialize()
    -- self:Print("插件加载!")
end

-- 启用插件时
function app:OnEnable()
    -- self:Print("欢迎使用! ")
    -- 注册事件
    -- 玩家进入世界
    self:RegisterEvent("PLAYER_ENTERING_WORLD", Update)
    -- 目标改变
    self:RegisterEvent("PLAYER_TARGET_CHANGED")
    -- 玩家进入战斗状态
    self:RegisterEvent("PLAYER_ENTER_COMBAT")
    -- 玩家离开战斗状态
    self:RegisterEvent("PLAYER_LEAVE_COMBAT")
    -- 监听玩家血量、蓝量和能量变化事件
    self:RegisterEvent("UNIT_HEALTH")
    self:RegisterEvent("UNIT_POWER_UPDATE")
end

-- 	玩家进入世界
function app:PLAYER_ENTERING_WORLD()
    -- self:Print("进入游戏!")
    CheckStatus()
end
-- 玩家进入战斗状态
function app:PLAYER_ENTER_COMBAT()
    oUFAlpha(1, true)
end
-- 玩家离开战斗
function app:PLAYER_LEAVE_COMBAT()
    CheckStatus()
end

-- 更换目标
function app:PLAYER_TARGET_CHANGED()
    if UnitExists("target") then
        -- self:Print("当前目标: " .. UnitName("target"))
        oUFAlpha(1, true)
    else
        -- self:Print("当前没有目标")
        -- oUFAlpha()
        CheckStatus()
    end
end
-- 单位血量健康
function app:UNIT_HEALTH(event, unit)
    CheckStatus()
end

-- 蓝量/能量
function app:UNIT_POWER_UPDATE(event, unit, powerType)
    CheckStatus()
end


-- 设置头像透明度
function oUFAlpha(alpha,status)
    alpha = alpha or 0
    status = status or false 
    oUF_Player:EnableMouse(status)
    oUF_Player:SetAlpha(alpha)
    oUF_Player.backdrop:SetAlpha(alpha)

    oUF_Pet:EnableMouse(status)
    oUF_Pet:SetAlpha(alpha)

    -- 判断 状态
    if status == false then
        oUF_Player.Health:Hide()
        oUF_Player.Power.backdrop:Hide()
    else
        oUF_Player.Health:Show()
        oUF_Player.Power.backdrop:Show()
    end

end

-- 检测 状态
function CheckStatus(unit)
    unit = unit or 'player'
    -- 血量
    local health = UnitHealth(unit)
    local maxHealth = UnitHealthMax(unit)

    -- 蓝量
    local mana = UnitPower(unit)
    local maxMana = UnitPowerMax(unit)
    local energy = UnitPower(unit, Enum.PowerType.Energy)


    local class = UnitClass("player")
    --有蓝职业--
    if not (class == "ROGUE") or not (class == "WARRIOR") then
        -- 判断 满血满蓝：透明度0
        if health == maxHealth and mana == maxMana then
            oUFAlpha()
        else
            oUFAlpha(1, true)
        end
    end
    --无蓝职业满血满蓝能量：透明度0--
    if (class == "ROGUE") or (class == "WARRIOR") then
        -- 判断 满血满能量：透明度0
        if health == maxHealth and energy == 100 then
            oUFAlpha()
        else
            oUFAlpha(1, true)
        end
    end
end